
const { ccclass, property } = cc._decorator;

/** 事件注册分发工具
 * @author david
 * 
 */
@ccclass
class BaseCustomEvent {

    functions = {};
    /** 注册一个事件
     * 
     * @param callbackName 
     * @param callback 
     * @param node
     * 
     */
    on(callbackName: string, callback: Function, node: cc.Node) {
        cc.log("on ", arguments)
        if (!this.functions[callbackName]) {
            this.functions[callbackName] = {};
        }
        this.functions[callbackName][node.uuid] = {
            c: callback,
            n: node
        };
    }

    /** 注销一个事件
     * 
     * @param callbackName 
     * @param node
     */
    off(callbackName: string, node: cc.Node) {
        cc.log("off ", arguments)

        if (!node) {
            cc.error("注销事件时发生错误,参数错误", arguments)
            return
        }
        if (this.functions[callbackName] && this.functions[callbackName][node.uuid]) {
            delete this.functions[callbackName][node.uuid]
            if (Object.keys(this.functions[callbackName]).length == 0) {
                delete this.functions[callbackName]
            }
        } else {
            cc.warn("注销事件时发生错误,事件不存在", this.functions, arguments)
        }
    }

    /** 广播一个事件
     * 
     * @param callbackName 
     * @param data 
     */
    emit(callbackName: string, data?: any) {
        cc.log("emit ", callbackName, data)
        let functionO = this.functions[callbackName]
        if (functionO) {
            for (const key in functionO) {
                let cn = functionO[key];
                if (cn.n && cn.n.isValid) {
                    cn.c(data);
                } else {
                    cc.warn("节点已失效", cn.n);
                    // this.off(callbackName, cn.n);
                }

            }
        } else {
            cc.warn("不存在此事件监听", callbackName)

        }
    }
}
export default new BaseCustomEvent()